package cn.ymatrix.mxgateSDKRabbitMQTOYMatrix;

import cn.ymatrix.utils.Config;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class RabbitMQConsumerWrapper {
  private final String QUEUE_NAME = Config.getQueueName();
  private final String QUEUE_HOST = Config.getQueueHost();
  private final String QUEUE_USERNAME = Config.getQueueUserName();
  private final String QUEUE_PASSWORD = Config.getQueuePassword();
  private final boolean queueISexist = Config.isQueueISexist();

  private final int ThreadSleepTime = Config.getQueueThreadSleepTime();

  public void consumeMessageLoop(RabbitMQMsgConsumeCallback callback)
      throws IOException, TimeoutException {

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost(QUEUE_HOST);
    factory.setUsername(QUEUE_USERNAME);
    factory.setPassword(QUEUE_PASSWORD);

    try (Connection connection = factory.newConnection();
        Channel channel = connection.createChannel()) {
      channel.queueDeclare(QUEUE_NAME, queueISexist, false, false, null);
      DeliverCallback deliverCallback =
          (consumerTag, delivery) -> {
            String rabbitMQMessage = new String(delivery.getBody(), StandardCharsets.UTF_8);
            callback.convertRabbitMQMsgValueToObj(rabbitMQMessage);
          };
      boolean autoAck = true;
      channel.basicConsume(QUEUE_NAME, autoAck, deliverCallback, consumerTag -> {});
      while (true) {
        // 阻塞线程，避免立即退出
        Thread.sleep(ThreadSleepTime);
      }
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
}
